package com.history.app;

import java.awt.BorderLayout;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.history.business.ArticleManager;
import com.history.common.Logit;
import com.history.common.RandomHelper;
import com.history.common.SpringContextFactory;
import com.history.common.file.FileProcess;
import com.history.domain.bean.Article;

public class SwingDragDrop {
	private static Logit log = Logit.getInstance(SwingDragDrop.class);

	String articleId;
	JLabel lbl;
	JTextField txtTitle;
	JTextArea  txtArea;
	JButton    btnSubmit;

	public SwingDragDrop() {
		JFrame frame = new JFrame("Local App");
		lbl 		= new JLabel("Edit Article.");
		txtTitle 	= new JTextField(20);
		txtArea   	= new JTextArea(10,10);
		btnSubmit 	= new JButton("Submit");
		btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
            	
            	Article article = new Article();
            	article.setId(articleId);
            	article.setTitle(txtTitle.getText());
            	article.setContent(txtArea.getText());
            	
            	// Init local manager
            	ArticleManager articleManagerLocal = SpringContextFactory.getArticleManager(false);
            	ArticleManager articleManager 	   = SpringContextFactory.getArticleManager(true);
            	try {
            		// Update article into Local database
					String key = RandomHelper.generateRandomKey();
					article.setSysKey(key);
            		articleManagerLocal.updateArticle(article);

					try {
						// Update article into Server database
	            		articleManager.updateArticle(article);
					} catch (Exception e) {
						// If the network is disconnected or has trouble.
						// save article id and action into text files
						String line = article.getId() +","+ key;						
						FileProcess.write(line);
					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);					
				}
            }
        });

		
		JPanel panel = new JPanel();
		panel.add(lbl, BorderLayout.CENTER);
		panel.add(txtTitle);
		
		txtArea.setSize(30, 30);
		panel.add(txtArea);
		panel.add(btnSubmit);
		
		frame.add(panel, BorderLayout.CENTER);

		frame.setSize(800, 800);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
	}

	public void setId(String id) {
		articleId = id;
	}

	public void setTitle(String title) {
		txtTitle.setText(title);
	}
	
	public void setContent(String content) {
		txtArea.setText(content);
	}
}